#!/sbin/openrc-run

description="Rapid mail filter"
command=/usr/sbin/rmilter
command_args=${cfgfile:+"-c $cfgfile"}

: ${user:=rmilter}
: ${group:=rmilter}
: ${cfgfile:=/etc/rmilter/rmilter.conf}

pidfile=$(grep '^[[:space:]]*pidfile[[:space:]]*=' $cfgfile | sed 's/[[:space:];]//g' | cut -d= -f2)
required_files="$cfgfile"
extra_started_commands="reload"
description_reload="Reload configuration"
start_stop_daemon_args="$start_stop_daemon_args --user $user --group $group"

depend() {
	need net localmount
	use logger antivirus antispam
	for file in $(ls /etc/conf.d/${RC_SVCNAME}-rc_need@* 2>/dev/null); do
		need ${file#*@}
	done
}

start_pre() {
	ebegin
	checkpath --directory --owner $user:$group ${pidfile%/*}
	bind_socket=$(grep '^[[:space:]]*bind_socket[[:space:]]*=[[:space:]]*unix:' $cfgfile | sed 's/[[:space:];]//g' | cut -d: -f2)
	diff_dir=$(grep -hr '^[[:space:]]*diff_dir[[:space:]]*=' ${cfgfile%/*} | sed 's/[[:space:];]//g' | cut -d= -f2)
	if [ "$bind_socket" ]; then
		checkpath --directory --owner $user:$group ${bind_socket%/*}
		rm -f $bind_socket
	fi
	if [ "$diff_dir" ]; then
		checkpath --directory --owner $user:$group $diff_dir
		rm -f $diff_dir/*
	fi
	eend $?
}

reload() {
	ebegin "Reloading ${RC_SVCNAME}"
	start-stop-daemon --signal USR1 --pidfile $pidfile
	eend $?
}
